package com.innovation.ic.cyz.base.service.cyz.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.cyz.base.mapper.cyz.DeviceSelectionMapper;
import com.innovation.ic.cyz.base.mapper.cyz.DeviceSelectionTypeMapper;
import com.innovation.ic.cyz.base.model.cyz.Categories;
import com.innovation.ic.cyz.base.model.cyz.DeviceSelection;
import com.innovation.ic.cyz.base.model.cyz.DeviceSelectionParameter;
import com.innovation.ic.cyz.base.model.cyz.DeviceSelectionType;
import com.innovation.ic.cyz.base.pojo.constant.deviceSelectionType.DeviceSelectionTypeConstant;
import com.innovation.ic.cyz.base.pojo.enums.DeviceSelectionToConfigureEnum;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.variable.cyz.PsCategoryPropertyPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.UploadImagePojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_type.DeviceSelectionChildrenParamPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_type.DeviceSelectionTypePojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_type.DeviceSelectionTypeQueryRespPojo;
import com.innovation.ic.cyz.base.service.cyz.DeviceSelectionParameterService;
import com.innovation.ic.cyz.base.service.cyz.DeviceSelectionService;
import com.innovation.ic.cyz.base.service.cyz.DeviceSelectionTypeService;
import com.innovation.ic.cyz.base.vo.cyz.AddDeviceSelectionToConfigureVo;
import com.innovation.ic.cyz.base.vo.cyz.DeviceSelectionToConfigureVo;
import com.innovation.ic.cyz.base.vo.cyz.deviceselection.AddDeviceSelectionParamVo;
import com.innovation.ic.cyz.base.vo.cyz.deviceselection.AddDeviceSelectionTypeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class DeviceSelectionServiceImpl extends ServiceImpl<DeviceSelectionMapper, DeviceSelection> implements DeviceSelectionService {
    @Resource
    private DeviceSelectionTypeService deviceSelectionTypeService;

    @Resource
    private DeviceSelectionParameterService deviceSelectionParameterService;

    @Resource
    private DeviceSelectionMapper deviceSelectionMapper;

    @Resource
    private DeviceSelectionTypeMapper deviceSelectionTypeMapper;

    /**
     * 查询器件选型菜单
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<DeviceSelectionChildrenParamPojo>> findDeviceSelectionMenu() {
        // 查询器件选型菜单数据
        List<DeviceSelectionChildrenParamPojo> result = findDeviceSelectionMenuData();

        ServiceResult<List<DeviceSelectionChildrenParamPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    @Override
    public List<DeviceSelection> findByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<DeviceSelection> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date");
        return deviceSelectionMapper.selectList(queryWrapper);
    }

    @Override
    public Integer selectCount() {
        return deviceSelectionMapper.selectCount(new QueryWrapper<>());
    }

    /**
     * 查询器件选型类别
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<DeviceSelectionTypeQueryRespPojo>> findDeviceSelection() {
        List<DeviceSelectionTypeQueryRespPojo> result = deviceSelectionMapper.findDeviceSelection();

        ServiceResult<List<DeviceSelectionTypeQueryRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult addDeviceSelection(AddDeviceSelectionParamVo addDeviceSelectionParamVo) {
        ServiceResult serviceResult = new ServiceResult();
       /* //校验是否添加重复
        Category categoryRoot = addDeviceSelectionParamVo.getCategoryRoot();
        QueryWrapper<DeviceSelectionType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("external_unique_id", categoryRoot.getId());
        queryWrapper.notIn("creator_id", "2");
        List<DeviceSelectionType> deviceSelectionTypes = deviceSelectionTypeService.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(deviceSelectionTypes)) {
            serviceResult.setMessage("不能重复添加");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
        //入库分类
        DeviceSelectionTypeVo deviceSelectionTypeVo = new DeviceSelectionTypeVo();
        deviceSelectionTypeVo.setName(categoryRoot.getName());
        deviceSelectionTypeVo.setCreatorId("2");
        deviceSelectionTypeVo.setCreateDate(new Date());
        deviceSelectionTypeVo.setExternalUniqueId(categoryRoot.getId());
        deviceSelectionTypeService.insert(deviceSelectionTypeVo);
        //同时入库详情
        DeviceSelection deviceSelection = new DeviceSelection();
        deviceSelection.setName(categoryRoot.getName());
        deviceSelection.setCreatorId("2");
        deviceSelection.setDeviceSelectionTypeId(deviceSelectionTypeVo.getId());
        deviceSelection.setEnable(1);
        deviceSelection.setCreateDate(new Date());
        deviceSelection.setExternalUniqueId(categoryRoot.getId());
        this.save(deviceSelection);
        List<CategoriesPropertyVo> categoriesPropertys = addDeviceSelectionParamVo.getCategoriesPropertys();
        List<DeviceSelectionParameterVo> deviceSelectionParameters = new ArrayList<>();
        for (CategoriesPropertyVo categoriesPropertyVo : categoriesPropertys) {
            DeviceSelectionParameterVo deviceSelectionParameterVo = new DeviceSelectionParameterVo();
            deviceSelectionParameterVo.setType(categoriesPropertyVo.getType());
            deviceSelectionParameterVo.setName(categoriesPropertyVo.getPropertyName());
            deviceSelectionParameterVo.setDeviceSelectionTypeId(deviceSelectionTypeVo.getId());
            deviceSelectionParameterVo.setExternalUniqueId(categoriesPropertyVo.getId());
            deviceSelectionParameterVo.setCreateDate(new Date());
            deviceSelectionParameters.add(deviceSelectionParameterVo);
        }*/
        //deviceSelectionParameterService.insertBatch(deviceSelectionParameters);
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult addDeviceSelectionType(Categories categories, AddDeviceSelectionTypeVo addDeviceSelectionTypeVo) {
        ServiceResult serviceResult = new ServiceResult();
        //String id = categoryRoot.getId();
        //添加器件选型分类,根节点
       /* DeviceSelectionType deviceSelectionType = deviceSelectionTypeService.findById(id);
        if (deviceSelectionType == null) {
            DeviceSelectionType saveDeviceSelectionType = new DeviceSelectionType();
            saveDeviceSelectionType.setId(id);
            saveDeviceSelectionType.setName(categoryRoot.getName());
            saveDeviceSelectionType.setCreatorId(addDeviceSelectionTypeVo.getCreatorId());
            saveDeviceSelectionType.setCreateDate(new Date());
            deviceSelectionTypeService.insert(saveDeviceSelectionType);
        }*/
        //同时添加首页器件选型首页
        DeviceSelection deviceSelection = this.baseMapper.selectById(categories.getId());
        if (deviceSelection == null) {
            deviceSelection = new DeviceSelection();
            deviceSelection.setId(categories.getId());
            deviceSelection.setName(addDeviceSelectionTypeVo.getName());
            deviceSelection.setEnable(0);
            deviceSelection.setCreatorId(addDeviceSelectionTypeVo.getCreatorId());
            deviceSelection.setCreateDate(new Date());
            this.baseMapper.insert(deviceSelection);
        }
        StringBuffer bottomId = new StringBuffer();
        //分类名字
        List<String> names = new ArrayList<>();
        StringBuffer nameBuffer = new StringBuffer();
        //递归解析
        recursionDeviceSelectionType(bottomId, names, addDeviceSelectionTypeVo, addDeviceSelectionTypeVo.getCreatorId());
        for (String name : names) {
            nameBuffer.append(name + "/");
        }
        nameBuffer.deleteCharAt(nameBuffer.length() - 1);
        //更新最底层节点标识,和层级名字
        deviceSelectionTypeService.updateBottom(bottomId.toString(), nameBuffer.toString());
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(bottomId);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<DeviceSelectionTypePojo>> findByDeviceSelectionToConfigure() {
        ServiceResult<List<DeviceSelectionTypePojo>> serviceResult = new ServiceResult<>();
        List<DeviceSelectionTypePojo> deviceSelectionTypeList = new ArrayList<>();

        QueryWrapper<DeviceSelectionType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bottom", 1);
        queryWrapper.orderByDesc("create_date");
        ServiceResult<List<DeviceSelectionType>> listServiceResult = deviceSelectionTypeService.selectList(queryWrapper);
        if (listServiceResult != null && !CollectionUtils.isEmpty(listServiceResult.getResult())) {
            List<DeviceSelectionType> deviceSelectionTypes = listServiceResult.getResult();
            for (DeviceSelectionType deviceSelectionType : deviceSelectionTypes) {
                DeviceSelectionTypePojo deviceSelectionTypePojo = new DeviceSelectionTypePojo();
                deviceSelectionTypePojo.setId(deviceSelectionType.getId());
                deviceSelectionTypePojo.setName(deviceSelectionType.getName());
                deviceSelectionTypePojo.setFatherId(deviceSelectionType.getFatherId());
                deviceSelectionTypePojo.setLevelName(deviceSelectionType.getLevelName());
                deviceSelectionTypeList.add(deviceSelectionTypePojo);
            }
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(deviceSelectionTypeList);
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult addDeviceSelectionToConfigure(AddDeviceSelectionToConfigureVo addDeviceSelectionToConfigureVo) {
        ServiceResult<List<DeviceSelectionTypePojo>> serviceResult = new ServiceResult<>();
        String deviceSelectionTypeId = addDeviceSelectionToConfigureVo.getDeviceSelectionTypeId();
        List<DeviceSelectionToConfigureVo> deviceSelectionToConfigureVo = addDeviceSelectionToConfigureVo.getDeviceSelectionToConfigureVo();
        //每次添加之前都要清空数据库
        deviceSelectionParameterService.deleteByTypeId(deviceSelectionTypeId);
        //保存配置
        for (DeviceSelectionToConfigureVo selectionToConfigureVo : deviceSelectionToConfigureVo) {
            if (!StringUtils.validateParameter(selectionToConfigureVo.getCategoriesPropertyId())) {
                continue;
            }
/*            List<Map<String, String>> list = DeviceSelectionToConfigureEnum.getList();
            if (list.contains(selectionToConfigureVo.getCategoriesPropertyId())) {
                for (Map<String, String> configureMap : list) {
                    if (configureMap.get("id").equals(selectionToConfigureVo.getCategoriesPropertyId())) {
                        DeviceSelectionParameter deviceSelectionParameter = new DeviceSelectionParameter();
                        deviceSelectionParameter.setType(selectionToConfigureVo.getType());
                        deviceSelectionParameter.setName(DeviceSelectionToConfigureEnum.BRAND.getName());
                        deviceSelectionParameter.setDeviceSelectionTypeId(deviceSelectionTypeId);
                        deviceSelectionParameter.setCreateDate(new Date());
                        deviceSelectionParameter.setExternallyUniqueId(DeviceSelectionToConfigureEnum.BRAND.getId());
                        deviceSelectionParameterService.insert(deviceSelectionParameter);
                        continue;
                    }
                }
            }*/
            DeviceSelectionParameter deviceSelectionParameter = new DeviceSelectionParameter();
            deviceSelectionParameter.setType(selectionToConfigureVo.getType());
            deviceSelectionParameter.setName(selectionToConfigureVo.getName());
            deviceSelectionParameter.setDeviceSelectionTypeId(deviceSelectionTypeId);
            deviceSelectionParameter.setCreateDate(new Date());
            deviceSelectionParameter.setExternallyUniqueId(selectionToConfigureVo.getCategoriesPropertyId());
            deviceSelectionParameterService.insert(deviceSelectionParameter);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult deleteDeviceSelectionType(String id) {
        ServiceResult serviceResult = new ServiceResult();
        if (!StringUtils.validateParameter(id)) {
            serviceResult.setSuccess(Boolean.TRUE);
            return serviceResult;
        }
        DeviceSelectionType deviceSelectionType = deviceSelectionTypeService.findById(id);
        //删除类型
        deviceSelectionTypeService.deleteById(id);
        //删除参数
        deviceSelectionParameterService.deleteByTypeId(id);
        //从底层开始向上查找
        QueryWrapper<DeviceSelectionType> queryWrapper = new QueryWrapper<>();
        ServiceResult<List<DeviceSelectionType>> deviceSelectionTypeResult = deviceSelectionTypeService.selectList(queryWrapper);
        List<DeviceSelectionType> deviceSelectionTypeList = deviceSelectionTypeResult.getResult();
        List<String> deleteRoot = new ArrayList<>();
        getParentLabelObject(deviceSelectionType, deviceSelectionTypeList, deleteRoot);
        for (String typeId : deleteRoot) {
            //查询是否有人在使用
            ServiceResult<Integer> integerServiceResult = deviceSelectionTypeService.checkValid(typeId);
            if (integerServiceResult != null && integerServiceResult.getResult() == 0) {
                deviceSelectionTypeService.deleteById(typeId);
            }
        }
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult<List<PsCategoryPropertyPojo>> getPsCategoriesProperty(String categoryId, List<PsCategoryPropertyPojo> psCategoriesProperty) {
        ServiceResult<List<PsCategoryPropertyPojo>> serviceResult = new ServiceResult<>();
        //找到当前类型
        Map<String, Object> param = new HashMap<>();
        param.put("device_selection_type_id", categoryId);
        List<DeviceSelectionParameter> deviceSelectionParameterList = deviceSelectionParameterService.selectByMap(param);
        //单独处理特殊数据
        List<Map<String, String>> list = DeviceSelectionToConfigureEnum.getList();
        for (Map<String, String> configureEnumMap : list) {
            PsCategoryPropertyPojo psCategoryPropertyPojo = new PsCategoryPropertyPojo();
            psCategoryPropertyPojo.setId(configureEnumMap.get("id"));
            psCategoryPropertyPojo.setPropertyName(configureEnumMap.get("name"));
            psCategoriesProperty.add(psCategoryPropertyPojo);
        }
        if (!CollectionUtils.isEmpty(deviceSelectionParameterList) && !CollectionUtils.isEmpty(psCategoriesProperty)) {
            for (PsCategoryPropertyPojo psCategoryPropertyPojo : psCategoriesProperty) {
                for (DeviceSelectionParameter deviceSelectionParameter : deviceSelectionParameterList) {
                    if (psCategoryPropertyPojo.getId().equals(deviceSelectionParameter.getExternallyUniqueId())) {
                        psCategoryPropertyPojo.setType(deviceSelectionParameter.getType());
                        psCategoryPropertyPojo.setExhibition(Boolean.TRUE);
                    }
                }
            }
        }
        serviceResult.setResult(psCategoriesProperty);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public ServiceResult updateDeviceSelectionTypePicture(UploadImagePojo uploadImagePojo) {
        ServiceResult serviceResult = new ServiceResult();
        //图片尺寸
        String pictureSize = "";
        //获取图片尺寸
        try {
            URL url = new URL(uploadImagePojo.getAbsoluteUrl());
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            BufferedImage image = ImageIO.read(connection.getInputStream());
            int srcWidth = image.getWidth();
            int srcHeight = image.getHeight();
            pictureSize = srcWidth+"x"+srcHeight;
        } catch (Exception e) {
            log.error("参数 {} ,获取图片尺寸出错",JSONObject.toJSONString(uploadImagePojo),e);
        }
        UpdateWrapper<DeviceSelection> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",uploadImagePojo.getUniqueId());
        updateWrapper.set("picture_path",uploadImagePojo.getAbsoluteUrl());
        updateWrapper.set("size",pictureSize);
        this.update(updateWrapper);
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 这里只做子节点处理
     *
     * @param addDeviceSelectionTypeVo
     */
    public void recursionDeviceSelectionType(StringBuffer bottomId, List<String> names, AddDeviceSelectionTypeVo addDeviceSelectionTypeVo, String creatorId) {
        if (addDeviceSelectionTypeVo == null) {
            return;
        }
        bottomId.delete(0, bottomId.length());
        names.add(addDeviceSelectionTypeVo.getName());
        //每次都要查询,是否保存
        String id = addDeviceSelectionTypeVo.getId();
        DeviceSelectionType deviceSelectionType = deviceSelectionTypeService.findById(id);
        if (deviceSelectionType == null) {
            deviceSelectionType = new DeviceSelectionType();
            deviceSelectionType.setId(id);
            deviceSelectionType.setName(addDeviceSelectionTypeVo.getName());
            deviceSelectionType.setCreatorId(creatorId);
            deviceSelectionType.setCreateDate(new Date());
            deviceSelectionType.setFatherId(addDeviceSelectionTypeVo.getParentId());
            deviceSelectionTypeService.insert(deviceSelectionType);
        }
        bottomId.append(id);
        recursionDeviceSelectionType(bottomId, names, addDeviceSelectionTypeVo.getChildId(), creatorId);
    }


    /**
     * 根据节点查找父节点
     * @param label
     * @return
     */
    public static void getParentLabelObject(DeviceSelectionType label, List<DeviceSelectionType> list, List<String> deleteRoot) {
        if (!StringUtils.validateParameter(label.getFatherId())) {
            return;
        }
        DeviceSelectionType l = list.stream().filter(
                x -> Objects.equals(x.getId(), label.getFatherId()
                )
        ).findFirst().get();
        String id = l.getId();
        deleteRoot.add(id);
        getParentLabelObject(l, list, deleteRoot);
    }

    /**
     * 查询器件选型菜单数据
     * @return 返回查询结果
     */
    private List<DeviceSelectionChildrenParamPojo> findDeviceSelectionMenuData() {
        List<DeviceSelectionChildrenParamPojo> result = new ArrayList<>();

        // 查询一级菜单
        List<DeviceSelectionType> deviceSelectionTypes = deviceSelectionTypeMapper.selectFirstLevelDeviceSelectionList();
        if(deviceSelectionTypes != null && deviceSelectionTypes.size() > 0){
            for(DeviceSelectionType deviceSelectionType : deviceSelectionTypes){
                DeviceSelectionChildrenParamPojo deviceSelectionChildrenParamPojo = new DeviceSelectionChildrenParamPojo();
                deviceSelectionChildrenParamPojo.setId(deviceSelectionType.getId());
                deviceSelectionChildrenParamPojo.setName(deviceSelectionType.getName());

                // 查询下级菜单
                List<JSONObject> lowerLevelMenuData = queryLowerLevelMenuDataById(deviceSelectionType.getId());
                if(!lowerLevelMenuData.isEmpty()){
                    deviceSelectionChildrenParamPojo.setChildren(lowerLevelMenuData);
                }
                result.add(deviceSelectionChildrenParamPojo);
            }
        }
        return result;
    }

    /**
     * 查询下级菜单
     * @param id 菜单id
     * @return 返回查询结果
     */
    private List<JSONObject> queryLowerLevelMenuDataById(String id) {
        List<JSONObject> lowerLevelMenuDataList = new ArrayList<>();

        // 根据id查询
        QueryWrapper<DeviceSelectionType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DeviceSelectionTypeConstant.FATHER_ID_FIELD, id);
        List<DeviceSelectionType> deviceSelectionTypes = deviceSelectionTypeMapper.selectList(queryWrapper);
        if(deviceSelectionTypes != null && deviceSelectionTypes.size() > 0){
            for(DeviceSelectionType deviceSelectionType : deviceSelectionTypes){
                JSONObject json = new JSONObject();
                json.put(DeviceSelectionTypeConstant.ID_FIELD, deviceSelectionType.getId());
                json.put(DeviceSelectionTypeConstant.NAME_FIELD, deviceSelectionType.getName());

                // 非最底层节点需要查询下级信息
                if(deviceSelectionType.getBottom() == null || deviceSelectionType.getBottom() != 1){
                    List<JSONObject> jsonObjects = queryLowerLevelMenuDataById(deviceSelectionType.getId());
                    if(jsonObjects.size() > 0){
                        json.put(DeviceSelectionTypeConstant.CHILDREN_FIELD, jsonObjects);
                        lowerLevelMenuDataList.add(json);
                    }
                }else{
                    lowerLevelMenuDataList.add(json);
                }
            }
        }
        return lowerLevelMenuDataList;
    }
}